package com.carhome.ui.fagment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.carhome.R;
import com.carhome.adapter.CarFragmentAdapter;
import com.carhome.bean.json.BrandList;
import com.carhome.bean.json.BrandResult;
import com.carhome.bean.json.CarBrandInfo;
import com.carhome.bean.json.CarInfo;
import com.carhome.bean.json.CarinfoList;
import com.carhome.ui.MainActivity;
import com.carhome.view.LetterView;
import com.carhome.view.LetterView.OnLetterChangeListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CarFragmentByBrand extends Fragment {
	// 视图中的Listview
	private ListView mListView;
	private CarFragmentAdapter mAdapter;

	// 覆盖在listview上面的视图，位于第一行
	private View viewOverlay;
	private TextView textviewOverlay;

	private HttpUtils mHttpUtils;

	// 字母导航视图
	private LetterView letterView;

	// 存储网络上获取的车信息
	private List<CarInfo> carInfosList;

	// 从网络上获取车分组列表信息网址
	String path = "http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635417325802968878.html";

	String alphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.car_fragment, container, false);
		initViews(view);
		setupViews();
		return view;
	}

	// 初始化数据
	private void setupViews() {
		carInfosList = new ArrayList<CarInfo>();
		mHttpUtils = new HttpUtils();
		mHttpUtils.send(HttpMethod.GET, path, httpRequest);
		letterView.setOnLetterChangeListener(letterChangeListener);
		mListView.setOnScrollListener(scrollListener);
		mListView.setOnItemSelectedListener(itemSelectedListener);
	}

	// 控件初始化函数
	private void initViews(View view) {
		mListView = (ListView) view.findViewById(R.id.car_fragment_listView);
		letterView = (LetterView) view.findViewById(R.id.car_fragment_letterView);
		viewOverlay = view.findViewById(R.id.car_fragment_viewOverlay);
		textviewOverlay = (TextView) view.findViewById(R.id.car_fragment_textviewOverlay);

	}

	RequestCallBack<String> httpRequest = new RequestCallBack<String>() {
		public void onFailure(HttpException paramHttpException, String paramString) {

		}

		public void onSuccess(ResponseInfo<String> paramResponseInfo) {
			String json = paramResponseInfo.result.toString();
			CarinfoList infoList = JSON.parseObject(json, CarinfoList.class);
			List<BrandList> brandLists = infoList.getResult().getBrandlist();

			for (Iterator iterator = brandLists.iterator(); iterator.hasNext();) {
				BrandList brandlist = (BrandList) iterator.next();
				String letter = brandlist.getLetter();
				List<CarBrandInfo> carlist = brandlist.getList();
				for (Iterator iteratorCar = carlist.iterator(); iteratorCar.hasNext();) {
					CarInfo carInfo = new CarInfo();
					CarBrandInfo carBrandInfo = (CarBrandInfo) iteratorCar.next();
					carInfo.setId(carBrandInfo.id);
					carInfo.setLetter(letter);
					carInfo.setName(carBrandInfo.name);
					carInfo.setImgurl(carBrandInfo.imgurl);
					carInfosList.add(carInfo);
				}
			}
			mAdapter = new CarFragmentAdapter(getActivity(), carInfosList);
			mListView.setAdapter(mAdapter);

		}
	};

	private OnLetterChangeListener letterChangeListener = new OnLetterChangeListener() {

		public void onLetterChange(int selectedIndex) {
			// 获取点击的字母
			String word = String.valueOf(alphas.charAt(selectedIndex));

			Iterator<CarInfo> listIterator = carInfosList.iterator();
			int count = 0;
			// 计算ListView需要跳转的地方
			while (listIterator.hasNext()) {
				CarInfo carInfo = listIterator.next();
				count++;
				if (word.equals(carInfo.letter)) {
					break;
				}
			}
			mListView.setSelection(count);	//设置listview要跳转的位置
		}
	};

	private OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		// firstVisibleItem 代表 第一个可见item的position
		// visibleItemCount 当前屏幕可见的item的个数
		// totalItemCount 代表ListView总的item个数
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
				int totalItemCount) {
			// 设置listview滚动的时候控制letterView中的字母
			if (carInfosList.size() != 0) {
				int index = alphas.indexOf(carInfosList
						.get(firstVisibleItem + visibleItemCount / 2).letter);
				letterView.setSelectedIndex(index);

				// 当前可见listview的第一个可见的item的下一个item正好是它所属分组的第一个元素的时候
				if(isFirstOfGroup(firstVisibleItem +1)){
					//获取ListView的第一个孩子视图
					View v = view.getChildAt(0);
					if(v == null){
						return;
					}
					int dex = v.getBottom() - textviewOverlay.getHeight();
//					System.out.println(v.getBottom());
					if(dex <= 0 ){
						viewOverlay.setPadding(0, dex, 0, 0);
						textviewOverlay.setText(carInfosList.get(firstVisibleItem +1).letter);
					}else{
						viewOverlay.setPadding(0, 0, 0, 0);
						textviewOverlay.setText(carInfosList.get(firstVisibleItem +1).letter);
					}
				}else {
					viewOverlay.setPadding(0, 0, 0, 0);
					textviewOverlay.setText(carInfosList.get(firstVisibleItem +1).letter);
				}
			}

		}

		// 判断当前item位置是否为分组的第一项
		private boolean isFirstOfGroup(int position) {
			if (carInfosList.size() != 0 && position != 0) {
				boolean tmp = carInfosList.get(position).letter.equals(carInfosList
						.get(position - 1).letter);
				System.out.println(carInfosList.get(position).name + !tmp );
				return !tmp;
			}
			return false;
		}
	};
	private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			
		}

		public void onNothingSelected(AdapterView<?> parent) {
			
		}
	};
}
